<template>
  <div class="app-container job">
    <div class="filter-container">
      <div class="search">
        <v-search
          input-placeholder="请输入用户"
          select-placeholder="请选择状态"
          start-date-placeholder="请选择添加开始时间"
          end-date-placeholder="请选择添加结束时间"
          :is-selecte="true"
          :selecte-list="selecteList"
          :is-download="false"
          :is-add="true"
          @onDownload="onDownload"
          @onSearch="onSearch"
          @onAdd="addNew"
        />
      </div>
    </div>
    <div>
      <el-table
        v-loading="isDataLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column label="编号" prop="sort_asc" sortable width="80" />
        <el-table-column
          v-for="(item, index) in field"
          :key="index"
          :label="item.title"
        >
          <template slot-scope="scope">
            <template v-if="String(item.name) === 'status'">
              {{ scope.row[item.name]|array_filter(selecteList) }}
            </template>
            <template v-else-if="String(item.name) === 'gid'">
              {{ scope.row[item.name]|array_filter(roleList) }}
            </template>
            <template v-else-if="String(item.name) === 'last_date'">
              {{ scope.row[item.name]|empty('未登录') }}
            </template>
            <template v-else-if="String(item.name) === 'last_ip'">
              {{ scope.row[item.name]|empty('未登录') }}
            </template>
            <template v-else-if="String(item.name) === 'last_address'">
              {{ scope.row[item.name]|empty('未登录') }}
            </template>
            <template v-else>
              {{ scope.row[item.name] }}
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <a @click.stop="see(scope.row)">修改</a>
            <a type="text" @click.stop="deleted(scope.row.id)">删除</a>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- 添加管理员 -->
    <el-dialog
      :title="form.id ? '修改管理员信息':'添加管理员信息'"
      :visible.sync="dialogVisible"
      width="520px"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" label-width="100px" :rules="rules" autocompconste="off">
        <el-form-item label="管理员账号" prop="username">
          <el-input v-model="form.username" placeholder="账号" />
        </el-form-item>
        <el-form-item label="管理员姓名" prop="nickname">
          <el-input v-model="form.nickname" placeholder="管理员姓名" />
        </el-form-item>
        <el-form-item label="管理员密码" prop="password">
          <el-input v-model="form.password" :placeholder="form.id ? '管理员密码(不填写不会修改密码)' : '管理员密码'" show-password />
          <a class="pointer" @click="createPassword">生成密码</a>
        </el-form-item>
        <el-form-item label="管理员权限" prop="gid">
          <el-select v-model="form.gid">
            <el-option
              v-for="(item, index) in roleList"
              :key="index"
              :label="item.name"
              :value="item.id"
              :disabled="item.id === -1"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" @click="cancel('form')">取 消</el-button>
          <el-button type="primary" size="mini" @click="saveEdit('form')">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import vSearch from '@/components/Search'
import { list, destroy, save } from '@/api/admin'
import { all } from '@/api/role'

export default {
  components: {
    Pagination,
    vSearch
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (!value && this.form.id === 0) {
        return callback(new Error('密码不能为空'))
      }
      if (value && value.length < 6) {
        callback(new Error('密码长度必须大于等于6位数'))
      } else {
        callback()
      }
    }
    return {
      multipleSelection: [],
      selecteList: [{
        id: 1,
        name: '正常'
      }, {
        id: 2,
        name: '锁定'
      }],
      total: 0,
      searchData: {},
      list: [],
      field: [],
      listQuery: {
        page: 1,
        limit: 5,
        where: []
      },
      selectedIds: [],
      selectedNames: '',
      title: '',
      type: '',
      dialogVisible: false,
      details: {},
      isDataLoading: false,
      roleList: [],
      form: {
        id: 0,
        gid: 1,
        username: '',
        password: '',
        nickname: '',
        status: 1
      },
      rules: {
        username: [
          { required: true, message: '请输入管理员名', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' }
        ],
        password: [{ validator: validatePass, trigger: 'blur' }],
        nickname: [{ required: true, message: '请输入管理员姓名', trigger: 'blur' }],
        gid: [{ required: true, message: '请输入管理员权限', trigger: 'change' }]
      }
    }
  },
  watch: {
    multipleSelection(newValue) {
      this.selectedIds = []
      this.selectedNames = ''
      if (newValue) {
        newValue.map(item => {
          this.selectedIds.push(item.program_id)
        })
      }
    }
  },
  created() {
    this.getList()
    this.getRoles()
    this.field = [{
      'name': 'id',
      'title': '主键'
    }, {
      'name': 'username',
      'title': '用户名'
    }, {
      'name': 'gid',
      'title': '所属群组'
    }, {
      'name': 'last_address',
      'title': '最后登录地点'
    }, {
      'name': 'last_date',
      'title': '最后登录时间'
    }, {
      'name': 'last_ip',
      'title': '最后登录IP'
    }, {
      'name': 'status',
      'title': '状态'
    }, {
      'name': 'create_time',
      'title': '添加日期'
    }, {
      'name': 'update_time',
      'title': '修改时间'
    }]
  },
  methods: {
    createPassword() {
      const text = [
        'abcdefghijklmnopqrstuvwxyz',
        'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        '1234567890'
      ]
      const rand = function(min, max) {
        return Math.floor(Math.max(min, Math.random() * (max + 1)))
      }
      const len = 12
      let pw = ''
      for (let i = 0; i < len; ++i) {
        const strpos = rand(0, 2)
        pw += text[strpos].charAt(rand(0, text[strpos].length))
      }
      this.form.password = pw
    },
    getRoles() {
      all().then(({ status, data }) => {
        if (status) {
          this.roleList = data
        }
        this.roleList.unshift({
          id: -1,
          name: '保留管理员'
        })
      })
    },
    onDownload(data) {
      console.log(data)
    },
    onSearch(data) {
      this.listQuery.where = []
      this.listQuery.page = 1
      if (data.keywords) {
        this.listQuery.where.push({
          field: '_.username',
          op: 'like',
          value: data.keywords
        })
      }
      if (data.selected) {
        this.listQuery.where.push({
          field: '_.status',
          op: 'eq',
          value: data.selected
        })
      }
      if (data.dateRange) {
        const start = data.dateStart
        const end = data.dateEnd
        this.listQuery.where.push({
          field: '_.create_time',
          op: 'between',
          value: [start, end]
        })
      }
      this.getList()
    },
    addNew() {
      this.dialogVisible = true
    },
    saveEdit(formName) {
      this.$refs[formName].validate(valid => {
        if (!valid) {
          return false
        }
        this.dialogVisible = false
        this.$store.commit('app/SHOW_LOADING')
        save(this.form).then(res => {
          this.$store.commit('app/HIDE_LOADING')
          if (res.status) {
            this.$message.success(res.msg)
            this.$refs[formName].resetFields()
            this.getList()
          }
        })
      })
    },
    cancel(formName) {
      this.$refs[formName].resetFields()
      this.form.id = 0
      this.dialogVisible = false
    },
    see(item) {
      this.form.id = item.id
      this.form.username = item.username
      this.form.nickname = item.nickname
      this.form.gid = item.gid
      this.form.status = item.status
      this.dialogVisible = true
    },
    deleted(id) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        destroy(id).then(res => {
          this.getList()
        })
      }).catch(() => { })
    },
    getList() {
      this.isDataLoading = true
      list(this.listQuery).then(res => {
        this.isDataLoading = false
        if (res.status) {
          this.list = res.data.data
          this.total = res.data.total
        }
      })
    }
  }
}
</script>

<style lang="scss" scpoed>
</style>
